from abc import ABCMeta, abstractmethod
import requests
import datetime
import random
from interface import Item, NOTIFY_TYPE, notify

# data = {
#     "account": "201821201",
#     "pwd": "19980825xhy"
# }


class XJG_Item(Item):
    def __init__(self) -> None:
        super().__init__()
        self.userdata = [
            {
                "account": "201821201",
                "pwd": "19980825xhy",
                "address": "江西省抚州市临川区抚河大道",
                "key": 'SCT123955TsWWh35vbsnQudgpFQjHMkGLx'
            },
            {
                "account": "201821184",
                "pwd": "xjg1234556",
                "address": "江西省丰城市梅林镇",
                "key": 'SCT102141TedAbdWYXmOoFCYEBjaNrJNi6'
            }, ]

    def setkey(self, key):
        self.key = key

    def notify(self, msg, title="掌上学工打卡", *args, **kwargs):
        """
        param {str} msg 消息内容
        param {str} title 标题
        return {None}
        """

        msg = {
            'title': title,
            'desp': f"工作台：http://xjgxg.jxufe.cn:63123/workstation.html\n\n查看入口：http://xjgxg.jxufe.cn:63123/HTML/JKDK1.html?v=1.9\n\n{msg}"
        }
        key = self.key
        if not key:
            return

        res = notify(NOTIFY_TYPE.FT, msg, key)
        if res and res.json()['code'] == 0:
            print(f"通知发送成功：", res.text)
        else:
            print("通知发送失败：", res.text)

    def check_login(self, data):
        self.setkey(data.get('key'))
        self.req = requests.Session()
        url = 'http://xjgxg.jxufe.edu.cn:7081/weixinYX/ashx/Phone_WXYX.ashx?type=Phone_CheckLogin'
        data = {
            "account": data.get('account'),
            "pwd": data.get('pwd')
        }
        header = {
            "Content-Type": 'application/x-www-form-urlencoded',
            "origin": "http://xjgxg.jxufe.edu.cn:7081",
            "Referer": 'http://xjgxg.jxufe.edu.cn:7081/xglogin.html',
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36"
        }
        response = self.req.post(
            url, data=data, headers=header, allow_redirects=False)
        sessionId = requests.utils.dict_from_cookiejar(
            response.cookies).get("ASP.NET_SessionId")
        if not sessionId:
            print(response.text)
            self.notify(f'打卡失败,返回数据:{response.text}')
            return False
        else:
            self.sessionId = sessionId
        return True

    def signin(self, data):
        if not self.sessionId:
            return

        url = "http://xjgxg.jxufe.cn:63123/weixinYX/ashx/Mobile_Handler.ashx?type=SaveXSTWSB1"
        data = {
            "TWSJ": "今日体温",
            # "SQDate": str(time.strftime('%Y-%m-%d',time.localtime(time.time()))),
            "SQDate": datetime.datetime.now().strftime("%Y-%m-%d"),
            "Temperature": f"36.{random.randint(1, 5)}",
            "TWZT": "正常",
            "address": data.get('address')
        }
        header = {
            "User-Agent": "Mozilla/5.0 (Linux; Android 10; EBG-AN00 Build/HUAWEIEBG-AN00; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/89.0.4389.72 MQQBrowser/6.2 TBS/045811 Mobile Safari/537.36 MMWEBID/2307 MicroMessenger/8.0.16.2040(0x28001055) Process/tools WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64",
            "Cookie": "ASP.NET_SessionId={}".format(self.sessionId)
        }
        re = self.req.post(url=url, data=data, headers=header, verify=False)
        if re.status_code == 200:
            print('打卡成功')
            self.notify('打卡成功')
        else:
            print("出现异常")
            self.notify('出现异常')

    def invoker(self, *args, **kwargs):
        for item in self.userdata:
            if self.check_login(item):
                self.signin(item)
